/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller;

import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.APIWarnException;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.table.MetaTableColumnRpcService;
import com.je.meta.rpc.table.MetaTableRpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 资源表-操作列
 */
@RestController
@RequestMapping(value = "/je/meta/resourceTable/table/column")
public class TableColumnController extends AbstractPlatformController {

    @Autowired
    private MetaTableColumnRpcService metaTableColumnRpcService;

    @Autowired
    private MetaTableRpcService metaTableRpcService;

    /**
     * 移除列
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doDelete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult removeColumn(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String tablecolumnTablecode = getStringParameter(request, "TABLECOLUMN_TABLECODE");
        if (StringUtil.isEmpty(tablecolumnTablecode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("column.code.notEmpty"));
        }
        dynaBean.set("TABLECOLUMN_TABLECODE", tablecolumnTablecode);
        String ids = param.getIds();
        String result = metaTableColumnRpcService.checkTypeById(ids);
        if(StringUtil.isNotEmpty(result)){
            return BaseRespResult.errorResult(result);
        }
        boolean isExist = metaTableColumnRpcService.checkIsExistForeignKeyByColumnIds(ids);
        Integer count = Integer.parseInt(metaTableColumnRpcService.removeColumnWithDll(dynaBean, ids));
        return BaseRespResult.successResult(isExist?"refresh":"1000", "", MessageUtils.getMessage("common.delete.success"));
    }

    /**
     * 增加字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addField", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult addField(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String funcinfoId = getStringParameter(request, "FUNCINFO_ID");
        if (StringUtil.isEmpty(funcinfoId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.id.canNotEmpty"));
        }
        dynaBean.setStr("JE_CORE_RESOURCETABLE_ID",getStringParameter(request,"JE_CORE_RESOURCETABLE_ID"));
        dynaBean.setStr("funcinfoId", funcinfoId);

        String result = metaTableColumnRpcService.addField(dynaBean);
        if(StringUtil.isNotEmpty(result)){
            return  BaseRespResult.errorResult(result);
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.save.success"));
    }

    /**
     * 添加字典辅助字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryDdColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult addColumnByDD(BaseMethodArgument param, HttpServletRequest request) {
        try {
            String ddCode = getStringParameter(request, "ddCode");
            if (StringUtil.isEmpty(ddCode)) {
                return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("dictionary.code.canNotEmpty"));
            }
            String isApply = getStringParameter(request, "isApply");
            DynaBean dynaBean = new DynaBean("JE_CORE_TABLECOLUMN",true);
            dynaBean.setStr("ddCode",ddCode);
            dynaBean.setStr("JE_CORE_RESOURCETABLE_ID",getStringParameter(request,"JE_CORE_RESOURCETABLE_ID"));
            dynaBean.setStr("addColumnCodes",getStringParameter(request,"addColumnCodes"));
            dynaBean.setStr("ddCode",getStringParameter(request,"ddCode"));
            dynaBean.setStr("ddName",getStringParameter(request,"ddName"));
            String result =  metaTableColumnRpcService.addColumnByDD(dynaBean);
            if(StringUtil.isNotEmpty(result)){
                return BaseRespResult.errorResult(result);
            }
            if ("1".equals(isApply)) {
                String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
                metaTableRpcService.updateTable(resourceId, true);
            }
            return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("common.add.success"));
        } catch (PlatformException pe) {
            return BaseRespResult.errorResult(pe.getErrorMsg());
        } catch (Exception e) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("common.add.error"));
        }

    }

    /**
     * 根据级联字典添加字段
     *
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryCasacdeDdColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult addAuxiliaryCasacdeDdColumn(BaseMethodArgument param, HttpServletRequest request) {
        String strData = getStringParameter(request,"strData");
        String pkValue = getStringParameter(request,"JE_CORE_RESOURCETABLE_ID");
        String whereSql = getStringParameter(request,"whereSql");
        String isApply = getStringParameter(request, "isApply");
        DynaBean dynaBean = new DynaBean();
        dynaBean.setStr("strData",strData);
        dynaBean.setStr("JE_CORE_RESOURCETABLE_ID",pkValue);
        dynaBean.setStr("whereSql",whereSql);
        String result = metaTableColumnRpcService.addColumnByDDList(dynaBean);
        if(StringUtil.isNotEmpty(result)){
            return BaseRespResult.errorResult(result);
        }
        if ("1".equals(isApply)) {
            String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
            metaTableRpcService.updateTable(resourceId, true);
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.add.success"));
    }

    /**
     * 根据表加字段
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryTableColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult addAuxiliaryTableColumn(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        String pkValue = getStringParameter(request,"JE_CORE_RESOURCETABLE_ID");
        String fromTableId = getStringParameter(request,"fromTableId");
        String createchild = getStringParameter(request,"CREATECHILD");
        String isApply = getStringParameter(request, "isApply");
        String FUNCCODE = getStringParameter(request, "FUNCCODE");
        String queryStr = getStringParameter(request, "queryStr");
        if (StringUtil.isNotEmpty(strData) && StringUtil.isNotEmpty(pkValue)) {
            DynaBean dynaBean = new DynaBean();
            dynaBean.setStr("strData",strData);
            dynaBean.setStr("JE_CORE_RESOURCETABLE_ID",pkValue);
            dynaBean.setStr("fromTableId",fromTableId);
            dynaBean.setStr("CREATECHILD",createchild);
            dynaBean.setStr("FUNCCODE",FUNCCODE);
            dynaBean.setStr("queryStr",queryStr);
            String result = metaTableColumnRpcService.addColumnByTable(dynaBean);
            if(StringUtil.isNotEmpty(result)){
                return BaseRespResult.errorResult(result);
            }
            if ("1".equals(isApply)) {
                String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
                metaTableRpcService.updateTable(resourceId, true);
            }
            return BaseRespResult.successResult(MessageUtils.getMessage("table.saveAuxiliary.success"));
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.illegal"));
        }
    }

    /**
     * 根据用户加字段
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/addAuxiliaryUserColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult addAuxiliaryUserColumn(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        String pkValue = getStringParameter(request,"JE_CORE_RESOURCETABLE_ID");
        String tableCode = getStringParameter(request,"tableCode");
        String queryStr = getStringParameter(request,"queryStr");
        String createchild = getStringParameter(request,"CREATECHILD");
        String funccode = getStringParameter(request,"FUNCCODE");
        String isApply = getStringParameter(request, "isApply");
        if (StringUtil.isNotEmpty(strData) && StringUtil.isNotEmpty(pkValue)) {
            DynaBean dynaBean = new DynaBean();
            dynaBean.setStr("strData",strData);
            dynaBean.setStr("JE_CORE_RESOURCETABLE_ID",pkValue);
            dynaBean.setStr("tableCode",tableCode);
            dynaBean.setStr("queryStr",queryStr);
            dynaBean.setStr("CREATECHILD",createchild);
            dynaBean.setStr("FUNCCODE",funccode);
            String result  = metaTableColumnRpcService.addColumnByTable(dynaBean);
            if(StringUtil.isNotEmpty(result)){
                return BaseRespResult.errorResult(result);
            }
            if ("1".equals(isApply)) {
                String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
                metaTableRpcService.updateTable(resourceId, true);
            }
            return BaseRespResult.successResult(MessageUtils.getMessage("table.saveAuxiliary.success"));
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.illegal"));
        }
    }

}
